package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.UserConstants;
import com.heima.common.exception.CustomException;
import com.heima.feign.Wemedia.IWemediaClient;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.Objects;

/**
 * @author 朱安东
 * @version 1.0
 * @project leadnews-project
 * @date 2024/1/26 11:21:10
 */
@Service
@Slf4j
@Transactional
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private IWemediaClient iWemediaClient;
    /**
     * 按状态查询页面
     *
     * @param authDto 身份验证 DTO
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult PageQueryByStatus(AuthDto authDto) {
        // 校验参数
        if (authDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 检查分页条件
        authDto.checkParam();
        // 根据状态进行分页查询
        Page page = new Page(authDto.getPage(), authDto.getSize());
        LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (authDto.getStatus() != null) {
            lambdaQueryWrapper.eq(ApUserRealname::getStatus, authDto.getStatus());
        }
        page = page(page, lambdaQueryWrapper);
        // 将分页结果返回给前端
        PageResponseResult pageResponseResult = new PageResponseResult(authDto.getPage(), authDto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());
        return pageResponseResult;
    }

    /**
     * 更新状态
     *
     * @param authDto 身份验证 DTO
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult updateStatus(AuthDto authDto) {
        // 校验参数
        if(authDto == null || authDto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 查询账号是否存在
        ApUserRealname apUserRealname = getById(authDto.getId());
        if(Objects.isNull(apUserRealname)){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        // 判断审核状态为成功或者失败
        // 驳回理由不为空则审核失败
        if(StringUtils.isNotBlank(authDto.getMsg())){
            update(Wrappers.<ApUserRealname>lambdaUpdate()
                    .eq(apUserRealname.getId() != null, ApUserRealname::getId, apUserRealname.getId())
                    .set(ApUserRealname::getStatus, UserConstants.FAIL_AUTH)
                    .set(ApUserRealname::getReason, authDto.getMsg()));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //4.如果状态为9则是审核通过，创建自媒体账号
        update(Wrappers.<ApUserRealname>lambdaUpdate()
                .eq(authDto.getId() != null, ApUserRealname::getId, authDto.getId())
                .set(ApUserRealname::getStatus, UserConstants.PASS_AUTH));
        createMediaAccount(apUserRealname);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 创建自媒体帐户
     *
     * @param apUserRealname AP 用户实名
     */
    private void createMediaAccount(ApUserRealname apUserRealname) {
        //1.参数校验
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());

        //1.1查询用户名，不存在则抛出异常
        if (Objects.isNull(apUser)) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //1.2存在则开通自媒体账号
        WmUser wmUser = iWemediaClient.getUsername(apUser.getName());

        //1.3判断账号是否存在
        if (Objects.nonNull(wmUser)) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST);
        }

        //2.封装参数
        wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        //密码加盐
        String md5Password = DigestUtils.md5DigestAsHex((wmUser.getPassword() + wmUser.getSalt()).getBytes());
        wmUser.setPassword(md5Password);
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        wmUser.setCreatedTime(new Date());

        //3.远程调用自媒体微服务
        iWemediaClient.createMediaAccount(wmUser);
    }
}
